package com.bear.forum.jdbc.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.bear.PlatFormDao.forum.TopicDao;
import com.bear.jdbc.impl.Page;
import com.bear.model.entity.User;
import com.bear.model.entity.forum.Topic;

@Repository
public class TopicDaoImp implements TopicDao{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<Topic> getAllTopicsPage(int page) {
		int  pageSize=10;
		Assert.isTrue(page>=1,"pageNo should start from 1");
		final List<Topic> topiclists = new ArrayList<Topic>();
		String countQueryString = "select count(*) from topic";
		long totalCount =  jdbcTemplate.queryForLong(countQueryString);
		if(totalCount<1)
			return topiclists;
		int startIndex = Page.getStartOfPage(page,pageSize);
		String query = "select t.id as id,t.title as title," +
				"t.author as author,t.content as content," +
				"t.topictime as topictime,t.photoaddress as photoaddress," +
				"t.isgood as isgood,t.replycount as replycount," +
				"u.username as authorname,u.photoAddress as header " +
				"from topic as t left JOIN user as u  on t.author=u.id" +
				" limit "+startIndex+","+pageSize;
		
		jdbcTemplate.query(query,
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
							Topic topic = new Topic();
							topic.setId(rs.getInt("id"));
							topic.setTitle(rs.getString("title"));
							User author = new User();
							author.setId(rs.getInt("author"));
							author.setUsername(rs.getString("authorname"));
							author.setPhotoAddress(rs.getString("header"));
							topic.setAuthor(author);
							topic.setContent(rs.getString("content"));
							topic.setTopictime(rs.getTimestamp("topictime"));
							topic.setPhotoaddress(rs.getString("photoaddress"));
							topic.setIsgood(rs.getInt("isgood"));
							topic.setReplycount(rs.getInt("replycount"));
							topiclists.add(topic);
					}
				});
		return topiclists;
	}

}
